<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 圈子点赞统计信息更新
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000011_t_sns_dynamic_stats_likes extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%sns_dynamic_like}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName)
        ->select(['dynamic_id', 'count(*) likes'])
        ->where([
            'and',
            ['!=', 'dynamic_id', 0],
            ['comment_id' => 0]
        ])
        ->groupBy('dynamic_id')
        ->having('count(*)>0');
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        foreach ($rows as $row) {
            $migration->db->createCommand()->update('{{%sns_dynamic_stats}}', [
                'likes' => $row['likes']
            ], ['dynamic_id' => $row['dynamic_id']])->execute();
        }
    }

}
